<template>
    <view class="container order-detail-container">
        <!-- 订单状态卡片 -->
        <view class="status-card">
            <view class="status-header">
                <text class="status-text" :class="getStatusClass(orderDetail.status)">{{getStatusText(orderDetail.status)}}</text>
            </view>
            <view class="status-info">
                <text class="status-desc">{{getStatusDescription(orderDetail.status)}}</text>
            </view>
        </view>
        
        <!-- 订单信息卡片 -->
        <view class="info-card">
            <view class="info-header">
                <text class="card-title">订单信息</text>
            </view>
            <view class="info-content">
                <view class="info-item">
                    <text class="item-label">订单编号</text>
                    <text class="item-value">{{orderDetail.orderNo || '暂无'}}</text>
                </view>
                <view class="info-item">
                    <text class="item-label">下单时间</text>
                    <text class="item-value">{{formatDateTime(orderDetail.create_time)}}</text>
                </view>
                <view class="info-item">
                    <text class="item-label">订单金额</text>
                    <text class="item-value price">¥ {{orderDetail.amount || 0}}</text>
                </view>
            </view>
        </view>
        
        <!-- 房间信息卡片 -->
        <view class="room-card">
            <view class="info-header">
                <text class="card-title">房间信息</text>
            </view>
            <view class="room-content">
                <view class="room-info">
                    <image class="room-image" 
                        :src="orderDetail.room_image || 'https://ai-public.mastergo.com/ai/img_res/dbef5d324519a8ea1d7dd7b355c94871.jpg'" 
                        mode="aspectFill"></image>
                    <view class="room-details">
                        <view class="room-name">{{orderDetail.room_name || '房间名称'}}</view>
                        <view class="room-time">时长：{{orderDetail.duration || 0}}小时</view>
                        <view class="room-reservation">
                            预订时段：{{formatDate(orderDetail.date)}} {{orderDetail.start_time}} 至 
                            {{orderDetail.is_next_day ? formatNextDay(orderDetail.date) : formatDate(orderDetail.date)}} {{orderDetail.end_time}}
                        </view>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 操作按钮区域 -->
        <view class="action-area">
            <!-- 根据订单状态显示不同按钮 -->
            <button v-if="orderDetail.status === 'canceled' || orderDetail.status === 'completed'" 
                class="action-btn" @click="deleteOrder(orderDetail.id)">删除订单</button>
            <button v-if="orderDetail.status === 'pending'" 
                class="action-btn pay-btn" @click="goToPay(orderDetail.id)">去付款</button>
            <button v-if="orderDetail.status === 'pending'" 
                class="action-btn" @click="cancelOrder(orderDetail.id)">取消订单</button>
            <button v-if="orderDetail.status === 'confirmed'" 
                class="action-btn contact-btn" @click="contactStore">联系商家</button>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getApiBaseUrl } from '../../utils/config.js';

// uni类型声明
declare const uni: any;

// 设置导航栏标题
uni.setNavigationBarTitle({
    title: '订单详情'
});

// 订单详情数据
const orderDetail = ref<any>({});
const loading = ref(false);

// 状态映射
const statusMap = {
    'pending': '待付款',
    'paid': '已支付',
    'confirmed': '未使用',
    'using': '使用中',
    'completed': '已完成',
    'canceled': '已取消'
};

// 状态描述映射
const statusDescMap = {
    'pending': '请在30分钟内完成支付，超时订单将自动取消',
    'paid': '订单已支付，等待商家确认',
    'confirmed': '订单已确认，可在预约时间到店使用',
    'using': '房间正在使用中',
    'completed': '服务已完成，欢迎再次光临',
    'canceled': '订单已取消'
};

// 获取状态对应的显示文本
const getStatusText = (status) => {
    return statusMap[status] || '未知状态';
};

// 获取状态对应的描述
const getStatusDescription = (status) => {
    return statusDescMap[status] || '';
};

// 获取状态对应的CSS类
const getStatusClass = (status) => {
    if (status === 'pending') return 'pending-status';
    if (status === 'canceled') return 'canceled-status';
    if (status === 'completed') return 'completed-status';
    if (status === 'using') return 'using-status';
    return '';
};

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
};

// 计算第二天日期
const formatNextDay = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    date.setDate(date.getDate() + 1);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
};

// 格式化日期时间
const formatDateTime = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 加载订单详情
const loadOrderDetail = async () => {
    try {
        const orderId = uni.getStorage({
            key: 'currentOrderId',
            success: function(res) {
                return res.data;
            },
            fail: function() {
                return null;
            }
        }) || getOrderIdFromUrl();
        
        if (!orderId) {
            uni.showToast({
                title: '订单ID不存在',
                icon: 'none'
            });
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
            return;
        }
        
        loading.value = true;
        
        // 调用API获取订单详情
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.navigateTo({ url: '/pages/login/login' });
            return;
        }

        const apiBaseUrl = getApiBaseUrl();
        
        const response = await uni.request({
            url: `${apiBaseUrl}/api/mobile/reservation/detail/${orderId}`,
            method: 'GET',
            header: {
                Authorization: `Bearer ${token}`
            }
        });
        
        // 兼容不同平台的响应格式
        const result = response.data || (response[1] && response[1].data);
        
        if (result && result.code === 200) {
            orderDetail.value = result.data || {};
        } else {
            uni.showToast({
                title: result && result.message || '获取订单详情失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取订单详情失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    } finally {
        loading.value = false;
    }
};

// 从URL中获取订单ID
const getOrderIdFromUrl = () => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage && currentPage.options && currentPage.options.id) {
        return currentPage.options.id;
    }
    return null;
};

// 取消订单
const cancelOrder = async (orderId) => {
    try {
        uni.showModal({
            title: '确认取消',
            content: '确定要取消此订单吗？',
            success: async (res) => {
                if (res.confirm) {
                    const token = uni.getStorageSync('token');
                    const apiBaseUrl = getApiBaseUrl();
                    
                    const response = await uni.request({
                        url: `${apiBaseUrl}/api/mobile/reservation/cancel/${orderId}`,
                        method: 'POST',
                        header: {
                            Authorization: `Bearer ${token}`
                        }
                    });
                    
                    // 兼容不同平台的响应格式
                    const result = response.data || (response[1] && response[1].data);
                    
                    if (result && result.code === 200) {
                        uni.showToast({
                            title: '订单已取消',
                            icon: 'success'
                        });
                        // 重新加载订单详情
                        loadOrderDetail();
                    } else {
                        uni.showToast({
                            title: result && result.message || '取消订单失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    } catch (error) {
        console.error('取消订单失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 删除订单
const deleteOrder = (orderId) => {
    uni.showModal({
        title: '确认删除',
        content: '确定要删除此订单吗？删除后无法恢复',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const token = uni.getStorageSync('token');
                    const apiBaseUrl = getApiBaseUrl();
                    
                    const response = await uni.request({
                        url: `${apiBaseUrl}/api/orders/delete/${orderId}`,
                        method: 'POST',
                        header: {
                            Authorization: `Bearer ${token}`
                        }
                    });
                    
                    // 兼容不同平台的响应格式
                    const result = response.data || (response[1] && response[1].data);
                    
                    if (result && result.code === 200) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                        // 返回上一页
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: result && result.message || '删除订单失败',
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    console.error('删除订单失败:', error);
                    uni.showToast({
                        title: '网络异常，请稍后重试',
                        icon: 'none'
                    });
                }
            }
        }
    });
};

// 跳转到支付页面
const goToPay = (orderId) => {
    uni.navigateTo({
        url: `/pages/pay/pay?id=${orderId}&businessType=reservation`
    });
};

// 联系商家
const contactStore = () => {
    uni.showModal({
        title: '联系商家',
        content: '确定要拨打商家电话吗？',
        success: function (res) {
            if (res.confirm) {
                uni.makePhoneCall({
                    phoneNumber: '18888888888',  // 这里替换为实际商家电话
                    fail: function () {
                        uni.showToast({
                            title: '拨打电话失败',
                            icon: 'none'
                        });
                    }
                });
            }
        }
    });
};

// 初始加载
onMounted(() => {
    loadOrderDetail();
});
</script>

<style>
page {
    background-color: #f5f5f5;
    min-height: 100%;
}

.order-detail-container {
    padding: 20rpx;
    padding-bottom: 120rpx;
}

/* 卡片通用样式 */
.status-card, .info-card, .room-card {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

/* 状态卡片样式 */
.status-card {
    padding: 30rpx;
}

.status-header {
    margin-bottom: 10rpx;
}

.status-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.status-info {
    margin-top: 10rpx;
}

.status-desc {
    font-size: 26rpx;
    color: #999;
}

.pending-status {
    color: #ff6600;
}

.canceled-status {
    color: #999;
}

.completed-status {
    color: #07c160;
}

.using-status {
    color: #1989fa;
}

/* 信息卡片样式 */
.info-header {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f1f1f1;
}

.card-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
}

.info-content {
    padding: 20rpx 30rpx;
}

.info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.info-item:last-child {
    margin-bottom: 0;
}

.item-label {
    color: #666;
    font-size: 28rpx;
}

.item-value {
    color: #333;
    font-size: 28rpx;
    text-align: right;
}

.price {
    color: #333;
    font-weight: bold;
}

/* 房间信息样式 */
.room-content {
    padding: 20rpx 30rpx;
}

.room-info {
    display: flex;
    align-items: flex-start;
}

.room-image {
    width: 180rpx;
    height: 180rpx;
    border-radius: 8rpx;
    margin-right: 24rpx;
    object-fit: cover;
}

.room-details {
    flex: 1;
}

.room-name {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 16rpx;
    font-weight: 500;
}

.room-time, .room-reservation {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 10rpx;
}

/* 操作区域样式 */
.action-area {
    display: flex;
    justify-content: flex-end;
    margin-top: 30rpx;
    padding: 0 20rpx;
    gap: 20rpx;
}

.action-btn {
    min-width: 180rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #fff;
    color: #666;
    font-size: 28rpx;
    padding: 0 30rpx;
    border: 1rpx solid #ddd;
    border-radius: 40rpx;
    margin: 0;
}

.pay-btn {
    background-color: #7FB992;
    color: #fff;
    border: none;
}

.contact-btn {
    background-color: #f8f8f8;
    color: #333;
    border-color: #ddd;
}
</style>